<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>在线聊天室测试</title>
    <link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body>
<style type="text/css" media="screen">
    body{background: #cecece;}
    .layui-container{display: none;position: absolute;left: 50%;top: 50%;margin-left: -585px;margin-top: -297.5px;}
    .im_submit{padding-right: 100px;position: relative;}
    .im_submit input{width: 100%;}
    .sendMessageBt{position: absolute;top: 0px;right: 0px;width: 100px;}
    .messageList{min-height: 200px;max-height: 500px;overflow: auto;width: 710px;padding-right: 10px;margin-bottom: 10px;}
    .messageList .noMessage{text-align: center;color: #999;}
    .messageList .noMessage i{font-size: 4em;line-height: 120px;}
    .messageList .noMessage span{font-size: 1.5em;}
    .messageItem{width: 100%;margin-bottom: 20px;}
    .messageItem .topinfo{height: 30px;line-height: 30px;color: #999;}
    .messageItem .topinfo .author{margin-right: 10px;}
    .messageItem .messageShow{border: 1px solid #ccc;background: #4caf50;color: #fff;padding: 5px 10px;border-radius: 5px;display: inline-block;position: relative;}
    .messageItem .messageShow .marker{position: absolute;width: 10px;height: 10px;top: -5px;left: 10px;background: #4caf50;transform:rotate(45deg);-ms-transform:rotate(45deg);-moz-transform:rotate(45deg);-webkit-transform:rotate(45deg);-o-transform:rotate(45deg);}
@media screen and (max-width:980px) {
 .layui-container {
  display: block;
  width: 100% !important;
  position: unset !important;
  margin: unset !important;
 }
}
    ::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}
::-webkit-scrollbar-button,
::-webkit-scrollbar-button:vertical {
  display: none;
}
::-webkit-scrollbar-track,
::-webkit-scrollbar-track:vertical {
  background-color: black;
}
::-webkit-scrollbar-track-piece {
  background-color: #f5f5f5;
}
::-webkit-scrollbar-thumb,
::-webkit-scrollbar-thumb:vertical {
  margin-right: 5px;
  background-color: #a6a6a6;
}
::-webkit-scrollbar-thumb:hover,
::-webkit-scrollbar-thumb:vertical:hover {
  background-color: #aaa;
}
::-webkit-scrollbar-corner,
::-webkit-scrollbar-corner:vertical {
  background-color: #535353;
}
::-webkit-scrollbar-resizer,
::-webkit-scrollbar-resizer:vertical {
  background-color: #ff6e00;
}
</style>

<div class="layui-container">
    <div class="layui-row layui-col-space30">
        <div class="layui-col-md8 layui-col-md-offset2">
            <div class="layui-card">
                <div class="layui-card-header"><span id="gname">在线聊天室</span> - <span class="theAuthor">管理员</span></div>
                <div class="layui-card-body">
                    <div class="messageList" id="messageList"></div>
                    <div class="sendMessage">
                        <form action="" class="im_submit" method="get" accept-charset="utf-8">
                            <input type="text" name="message" required="" lay-verify="required" placeholder="请输入消息内容" autocomplete="off" class="layui-input" id="messageInput">
                            <button lay-submit class="layui-btn sendMessageBt" lay-filter="sendMessageBt">发送</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" name="ws" host="127.0.0.1" port="5678" id="ws">
<input type="hidden" name="uid" value="" id="uid">
<input type="hidden" name="username" value="" id="username">
<input type="hidden" name="gname" value="" id="gname">
<input type="hidden" name="gid" value="" id="gid">

 
<script src="./layui/layui.js"></script>
<script>
    //一般直接写在一个js文件中
    layui.use(['layer', 'form', 'jquery'], function(){
        var layer = layui.layer,
        form = layui.form,
        $ = layui.jquery;

        var socket = false;
        var sendtoken = false;
        getViewData();

        
        function getViewData(){
            $.ajax({
                url: '/getUserInfo',
                type: 'POST',
                dataType: 'json',
                success: function(e){
                    if (e.code == 200) {
                        $('#uid').val(e.uid);
                        $('#username').val(e.username);
                        $('.theAuthor').text(e.username);
                        $.ajax({
                            url: '/getGroupChat',
                            type: 'POST',
                            dataType: 'json',
                            success: function(e){
                                if (e.code == 200) {
                                    $('input[name=gid]').val(e.gid);
                                    $('input[name=gname]').val(e.gname);
                                    $('input[name=ws]').val(e.ws);
                                    $('#gname').text(e.gname);
                                    $.ajax({
                                        url: '/getHistoryMessage',
                                        type: 'POST',
                                        dataType: 'json',
                                        data: {
                                            gid: $('input[name=gid]').val()
                                        },
                                        success: function(e){
                                            if (e.code == 200) {
                                                var listMessage = e.listMessage;
                                                showMessage(listMessage);
                                                setSocket();
                                            }else{
                                                layer.msg(e.msg);
                                            }
                                        }
                                    });
                                }else{
                                    layer.msg(e.msg);
                                }
                            }
                        });
                    }else{
                        layer.msg(e.msg);
                    }
                }
            });
        }

        function getMessageTokenAndSend(s){
            $.ajax({
                url: '/getMessageToken',
                type: 'POST',
                dataType: 'json',
                data:{
                    message: s,
                    gid: $('#gid').val()
                },
                success: function(e){
                    if (e.code == 200) {
                        socket.send(e.token);
                    }else{
                        layer.msg(e.msg);
                    }
                }
            });
        }

        function showlineHtml(itemMessage){
            return '<div class="messageItem"><div class="topinfo"><span class="author">'+itemMessage.author+'</span><span class="lasttime">'+itemMessage.dateline+'</span></div><div class="messageShow"><div class="marker"></div>'+itemMessage.message+'</div></div>';
        }
        
        function setMessageBox(){
            var messageList = document.getElementById('messageList');
            messageList.scrollTop = messageList.scrollHeight;
        }


        function showMessage(listMessage){
            var messageHtml = '';
            for (var i = 0; i <= listMessage.length - 1; i++) {
                var itemMessage = listMessage[i];
                messageHtml += showlineHtml(itemMessage);
            }
            if (messageHtml == '') {
                messageHtml = '<div class="noMessage"><i class="layui-icon layui-icon-face-surprised"></i><p>暂无新消息</p></div>';
            }
            $('.messageList').html(messageHtml);
            $('.layui-container').show();
            setMessageBox();
            layer.msg('获取历史消息成功');
        }

        function setSocket(){
            var socketServer = $('#ws').val();

            socket = new WebSocket(socketServer); 
            socket.onopen = function(){
                socketSend('#1##@@@@！#27941662####');
            }
            socket.onmessage = function(e){
                var obj = eval('(' + e.data + ')');
                html = showlineHtml(obj);
                $('.messageList').append(html);
                setMessageBox();
                $('.noMessage').hide();
            }
            socket.onclose = function(e){
                layer.msg('您和服务器的链接已断开');
            }
            socket.onerror = function(e){
                layer.msg('您和服务器的链接发生错误');
            }
        }

        function socketSend(message){
            if (socket.binaryType != 'blob') {
                layer.msg('消息发送失败：未能成功连接到服务器');
            }
            getMessageTokenAndSend(message);
            $('#messageInput').val('');
            return false;
        }

        form.on('submit(sendMessageBt)', function(data){
            var message = $('input[name=message]').val();
            if (message.length == 0) {
                layer.msg('请输入消息内容');
                return false;
            }
            socketSend(message);
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    });
</script> 
</body>
</html>